package com.example.yichuangyun.ui.fragment.view;

import androidx.lifecycle.MutableLiveData;

import com.example.yichuangyun.application.MyApplication;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.http.ApiFactory;
import com.example.yichuangyun.model.StatusModel;
import com.example.yichuangyun.model.UserInfoModel;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.mvvm.di.retrofit.BaseModel;
import com.example.yichuangyun.mvvm.di.retrofit.BaseNetCallback;
import com.example.yichuangyun.utils.ToastHelper;
import com.google.gson.Gson;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.subscribers.ResourceSubscriber;

public class MineViewModel extends BaseViewModel {

    public MutableLiveData<String> urlMutableLiveData = new MutableLiveData<>();
    public MutableLiveData<UserInfoModel> userInfoModelMutableLiveData = new MutableLiveData<>();

    /**
     * 图片上传
     */
    public void uploadImages(File file) {
        addSubscribe(mRetrofitHelper.uploadImage2(file).subscribeWith(new ResourceSubscriber<StatusModel>() {

            @Override
            public void onNext(StatusModel statusModel) {
                if (statusModel.getStatus() == 200) {
                    editThumbAvatar(ApiFactory.FILE_URL + statusModel.getId());
                }
            }

            @Override
            public void onError(Throwable t) {

            }

            @Override
            public void onComplete() {

            }
        }));
    }

    /**
     * 修改头像
     */
    public void editThumbAvatar(String url) {
        Map<String, Object> map = new HashMap<>();
        map.put("newThumbAvatar", url);
        addSubscribe(mRetrofitHelper.editThumbAvatar(new Gson().toJson(map)).subscribeWith(new BaseNetCallback<String>() {
            @Override
            public void onSuccess(BaseModel<String> baseModel) {
                if (Constant.SUCCESS == baseModel.getCode()) {
                    urlMutableLiveData.setValue(baseModel.getData());
                } else {
                    ToastHelper.show(baseModel.getMsg());
                }
            }

            @Override
            public void onError(String message) {
                super.onError(message);
                ToastHelper.show(message);
            }
        }));
    }

    /**
     * 个人信息
     */
    public void getUserInfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", MyApplication.manager.getId());
        addSubscribe(mRetrofitHelper.getUserInfo(new Gson().toJson(map)).subscribeWith(new BaseNetCallback<UserInfoModel>() {
            @Override
            public void onSuccess(BaseModel<UserInfoModel> baseModel) {
                if (Constant.SUCCESS == baseModel.getCode()) {
                    userInfoModelMutableLiveData.setValue(baseModel.getData());
                }
            }
        }));
    }
}
